﻿var usWin;
function BindGrid(){
        Ext.lib.Ajax.defaultPostHeader = 'application/json';
         var gridDiv = $get('grid-user');
         gridDiv.innerHTML = '';
         var fieldMap = new Ext.data.Record.create(
                    [
                        {name : 'LastName'},
                        {name : 'FirstName'}
 
                    ]);
 
                    var usDataStore = new Ext.data.Store(
                    {
                        //Note that I have renamed the web service proxy class
                        proxy: new Ext.ux.AspWebServiceProxy(
                        {
                            webServiceProxy: ExtJSWebService,
                            webServiceProxyMethod: ExtJSWebService.GetUserCollectionJSON
                        }),
                        reader: new Ext.data.JsonReader({
                                    root: 'List',
                                    totalProperty: 'TotalCount',
                                    id: 'LastName'
                        },fieldMap),
 
                        remoteSort: true
                    });
 
                    usDataStore.setDefaultSort('LastName', 'desc');
            // 5. Now you can bind this ExtJS based “Store” to any ExtJS based “GridPanel” or Select list or can use the store as a temporary data place holder for further manipulation later on.
            var usColModel = new Ext.grid.ColumnModel([
 
                {header: "Last Name", width: 105, sortable: true, dataIndex: 'LastName'},
                {header: "First Name", width: 105, sortable: true, dataIndex: 'FirstName'},
            ]);
 
            var usGrid = new Ext.grid.GridPanel({
                el:'grid-user',
                ds: usDataStore,
                cm: usColModel,
                sm: new Ext.grid.RowSelectionModel({
                   singleSelect: true
               }),
                stripeRows: true,
                bbar: new Ext.PagingToolbar({
                    pageSize: 10,
                    store: usDataStore,
                    displayInfo: true,
                    displayMsg: 'Displaying Users {0} - {1} of {2}',
                    emptyMsg: "No topics to display"
                    }),
                viewConfig: {
                    emptyText: '&lt;<span class="tag">div</span><span class="attr"> style=</span><span class="attrv">"color:Red;"</span><span class="attr"> align=</span><span class="attrv">"center"</span>&gt;No Users found...&lt;/<span class="tag">div</span>&gt;'
                },
                autoHeight:true,
                plugins:[new Ext.ux.grid.Search({
                             mode:'local'
                            ,iconCls:false
                            ,dateFormat:'m/d/Y'
                        })]
            });
            usGrid.render();
 
           usGrid.on('rowclick', function (grid, rowIndex, e){
                var record = grid.getStore().getAt(rowIndex);  // Get the Record
                var userID = record.data['LastName'];
                window.location='ManageUser.aspx?Mode=Update&amp;LastName='+LastName;
             });
 
            var paramXML = PrepareParamXML();
 
            usDataStore.on('beforeload', function() {
                        usDataStore.baseParams = {
                        i_Params: paramXML
                      };
             });
 
            usDataStore.load({params:{start:0, limit:10}});
            usDataStore.on('loadexception', function(a,conn,resp) {
                     if (resp.status == '304') {
                                //Ext.Msg.alert('Content has not changed');
                            } else if (resp.status == '401') {
                                //Ext.Msg.alert('Authentication required - You need to Login');
                            }
                });
 
        // create the window on the first click and reuse on subsequent clicks
        if(!usWin){
            usWin = new Ext.Window({
                el:'grid-win',
                layout:'fit',
                width:600,
                modal:true,
                autoHeight:true,
                closeAction:'hide',
                plain: true,
                items: [usGrid],
                buttons: [{
                    text: 'Close',
                    handler: function(){
                        usWin.hide();
                           var button = Ext.get('ctl00_ContentPlaceHolder1_btnSearch');
                           button.dom.focus();
                           var txt = Ext.get('ctl00_ContentPlaceHolder1_txtLastName');
                           txt.dom.focus();
                    }
                }]
            });
        }
        usWin.show();
        return false;
}
 
Ext.namespace('Ext.ux');
 
Ext.ux.AspWebServiceProxy = function(conn)
           {
              Ext.ux.AspWebServiceProxy.superclass.constructor.call(this);
              Ext.apply(this, conn);
           };
 
Ext.extend(Ext.ux.AspWebServiceProxy, Ext.data.DataProxy,
{
     load : function (params, reader, callback, scope, arg)
            {
               var userContext = {
                                    callback: callback,
                                    reader: reader,
                                    arg: arg,
                                    scope: scope
                                 };
 
               var proxyWrapper = this;
 
               //debugger;
               //Handles the response we get back from the web service call
               var webServiceCallback = function(response, context, methodName)
                                        {
                                            proxyWrapper.loadResponse(response, userContext, methodName);
                                        }
 
               var serviceParams = [];
 
               //Convert the params into an array of values so that they can be used in the call (note assumes that the properties on the object are in the correct order)
               for (var property in params)
               {
                  serviceParams.push(params[property]);
               }
 
               //Add the webservice callback handlers
               serviceParams.push(webServiceCallback);
               serviceParams.push(this.handleErrorResponse);
 
               //Make the actual ASP.Net web service call
               this.webServiceProxyMethod.apply(this.webServiceProxy, serviceParams);
            },
 
     handleErrorResponse : function(response, userContext, methodName)
                           {
                               window.location.reload();
//                               Ext.MessageBox.show({
//                                       title: 'Error',
//                                       msg: response.get_message(),
//                                       buttons: Ext.MessageBox.OK,
//                                       icon: Ext.MessageBox.ERROR
//                                   });
                              //alert("Error while calling method: " + methodName + "n" + response.get_message());
                           },
 
     loadResponse : function (response, userContext, methodName)
                    {
                        var result = userContext.reader.readRecords(response);
                        userContext.callback.call(userContext.scope, result, userContext.arg, true);
                    }
 
});